<?php

namespace app\adminapi\controller;

use think\Controller;
use think\Request;
use tools\jwt\Token;

class Common extends Controller
{
    //无需进行登录检测的请求
    protected $no_login = ['common/saveuser'];
    protected function _initialize()
    {
        parent::_initialize();
        try {
            $this->redis = new \Redis();
            $this->redis->connect('127.0.0.1', 6379);
        }catch (\Exception $e){
            $this->fail('redis 连接失败');
        }
        try{
            $path = strtolower($this->request->controller()) . '/' . $this->request->action();
            if(!in_array($path, $this->no_login)){
                $user_id = \tools\jwt\Token::getUserId();
                //登录验证
                $data =$this->redis->hGetAll($user_id);

                if(empty($data)){
                    $this->fail('未登录或Token无效', 403);
                }
                //将获取的用户id 设置到请求信息中
                $this->request->get(['user_id' => $user_id,'username'=>$data['username']]);
                $this->request->post(['user_id' => $user_id,'username'=>$data['username']]);
            }
        }catch(\Exception $e){
            $this->fail('服务异常，请检查token令牌', 403);
        }


    }
    /**
     * 创建一个用户
     */
    public function saveUser()
    {
        //接收数据
        $params = input();
        //验证数据
        $validate = $this->validate($params,[
            'username|用户名' => 'require',
            'password|密码' => 'require',
        ]);
        if($validate !== true){
            $this->fail($validate);
        }
        //获取自增id
        $id=$this->redis->incr('userid');
        //往redis里添加数据
        $this->redis->hmSet('user_'.$id,array('id'=>$id,'username'=>$params['username'],'password'=>$params['password']));
        $token = Token::getToken('user_'.$id);
        $this->ok(['token'=>$token]);
    }
    /**
     * 通用响应
     * @param int $code 状态码
     * @param string $msg 状态描述
     * @param array $data 返回数据
     */
    public function response($code=20,$msg='success',$data=[])
    {
        $res=[
            'code' => $code,
            'msg'  => $msg,
            'data' => $data
        ];
        json($res)->send();die();
    }

    /**
     * @param array $data 返回数据
     * @param int $code 状态码
     * @param string $msg 状态码描述
     * @return mixed
     */
    public function ok($data=[],$code=200,$msg='success')
    {
        return $this->response($code,$msg,$data);
    }

    /**
     * @param string $msg 错误信息
     * @param int $code 错误码
     * @return mixed
     */
    public function fail($msg='fail',$code=500)
    {
        return $this->response($code,$msg);
    }
}
